use async_std::task;
use std::env;
use std::time::Duration;
use systemstat::{Platform, System as SystemStat};
use tauri::Manager;

// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}
#[tauri::command]
fn os_info() -> String {
    tauri_plugin_os::platform().to_string()
}

#[tauri::command]
fn mem_usage() -> f64 {
    let sys = SystemStat::new();
    match sys.memory() {
        Ok(mem) => {
            ((mem.total.as_u64() as f64 - mem.free.as_u64() as f64) / mem.total.as_u64() as f64)
                * 100.0
        }
        Err(x) => 0f64,
    }
}

#[tauri::command]
fn get_current_path() -> String {
    match env::current_exe() {
        Ok(exe_path) => {
            // 获取父目录路径
            if let Some(mut parent_path) = exe_path.parent().map(|p| p.to_path_buf()) {
                // 确保路径末尾有分隔符
                parent_path.push(""); // 这会自动添加分隔符
                // 将 PathBuf 转换为字符串
                parent_path.to_string_lossy().to_string()
            } else {
                eprintln!("Failed to get parent directory of the executable path: {:?}", exe_path);
                String::new()
            }
        }
        Err(e) => {
            eprintln!("Failed to get current executable path: {}", e);
            // 返回一个空字符串或错误信息
            String::new()
        }
    }
}

#[tauri::command]
async fn cpu_usage() -> f64 {
    let sys = SystemStat::new();
    match sys.cpu_load_aggregate() {
        Ok(cpu) => {
            println!("\nMeasuring CPU load...");
            task::sleep(Duration::from_secs(1)).await;
            let cpu = cpu.done().unwrap();
            println!(
                "CPU load: {}% user, {}% nice, {}% system, {}% intr, {}% idle ",
                cpu.user * 100.0,
                cpu.nice * 100.0,
                cpu.system * 100.0,
                cpu.interrupt * 100.0,
                cpu.idle * 100.0
            );
            (cpu.idle * 100.0) as f64
        }
        Err(_x) => {
            println!("\nCPU load: error: {}", _x);
            0 as f64
        }
    }
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_http::init())
        .plugin(tauri_plugin_notification::init())
        .setup(|app| {
            #[cfg(debug_assertions)] // 仅在调试构建时包含此代码
            {
                let window = app.get_webview_window("main").unwrap();
                window.open_devtools();
                window.close_devtools();
            }
            Ok(())
        })
        // .setup(|app| {
        //     let stores = app.app_handle().state::<StoreCollection<Wry>>();
        //     let path = PathBuf::from("store.bin");
        //
        //     with_store(app.app_handle().clone(), stores, path, |store| {
        //         // 注意，值必须是 serde_json::Value 的实例，
        //         // 否则，它们将与 JavaScript 绑定不兼容。
        //         store.insert("some-key".to_string(), json!({ "value": 5 }))?;
        //
        //         // 从 Store 中获取一个值。
        //         let value = store.get("some-key").expect("Failed to get value from store");
        //         println!("{}", value); // {"value":5}
        //
        //         // 您可以在进行更改后手动保存存储
        //         // 否则如上所述，它将在正常退出时保存。
        //         store.save()?;
        //
        //         Ok(())
        //     });
        //
        //     Ok(())
        // })
        .plugin(tauri_plugin_window_state::Builder::new().build())
        .plugin(tauri_plugin_upload::init())
        .plugin(tauri_plugin_os::init())
        .plugin(tauri_plugin_store::Builder::new().build())
        .plugin(tauri_plugin_opener::init())
        .invoke_handler(tauri::generate_handler![
            greet,
            os_info,
            mem_usage,
            cpu_usage,
            get_current_path
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
